package com.example.seata.stock.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.example.seata.stock.entity.StorageTbl;
import com.example.seata.stock.mapper.StorageTblMapper;
import com.example.seata.stock.service.IStorageTblService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.example.enums.CommonErrorCode;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author tianshuo
 * @since 2021-05-15
 */
@Service
public class StorageTblServiceImpl extends ServiceImpl<StorageTblMapper, StorageTbl> implements IStorageTblService {

    @Transactional
    @Override
    public boolean deduct(StorageTbl storageTbl) {

        QueryWrapper<StorageTbl> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(StorageTbl::getCommodityCode, storageTbl.getCommodityCode());
        StorageTbl storageTbl1 = getOne(queryWrapper);

        if (storageTbl1.getCount() < storageTbl.getCount()) {
            throw new RuntimeException(CommonErrorCode.SYSTEM_INNER_ERROR.getDesc());
        }
        int count = storageTbl1.getCount()-storageTbl.getCount();
        UpdateWrapper<StorageTbl> updateWrapper = new UpdateWrapper<>();
        update(updateWrapper.lambda().eq(StorageTbl::getCommodityCode,storageTbl.getCommodityCode()).set(StorageTbl::getCount,count));

        return true;
    }
}
